package gd.hq.yolov5.comunicate;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.acl.LastOwnerException;

public class MyBlueDevice {
    private BluetoothDevice device = null;
    private BluetoothSocket socket = null;
    private InputStream inputStream = null;
    private OutputStream outputStream = null;

    public MyBlueDevice(BluetoothDevice device) {
        this.device = device;
    }

    public void sendMsg(String data) {
        Log.d("sendData", data);
        if (inputStream != null) {
            try {
                outputStream.write(data.getBytes());
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public boolean connect() {
        try {
            Log.d("TAG", "连接蓝牙");
            socket = device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
            //在连接过程中，会出现java.io.IOException: read failed, socket might                    closed or timeout, read ret: -1,目前还没什么找到太好的解决方案
            socket.connect();
            if (socket != null) {
                Log.d("TAG", "获取输入流");
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();
            }
//            byte[] bytes = new byte[100];
//            if (inputStream != null) {
//                while (true) {
//                    int read = inputStream.read(bytes);
//                    if(read>0){
//                        String data = new String(bytes,"GB2312");
//                        Log.d("read",data);
//                    }
//                }
//            }
        } catch (
                IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
